using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XUCore.Helpers;
using XUCore.WeChat.Helper;

namespace XUCore.WeChat
{
    public class WeChatWebSignature : IWeChatWebSignature
    {
        private readonly WeChatFuncs weChatFuncs;
        private readonly IWeChatTicketManager ticketManager;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="weChatFuncs"></param>
        /// <param name="ticketManager"></param>
        public WeChatWebSignature(WeChatFuncs weChatFuncs, IWeChatTicketManager ticketManager)
        {
            this.weChatFuncs = weChatFuncs;
            this.ticketManager = ticketManager;
        }

        /// <summary>
        /// 获取网页授权签名
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<WebSignatureResult> Create(WebSignatureRequest request)
        {
            var options = weChatFuncs.GetWeChatOptions(request.App);

            if (options == null)
                throw new WeChatSdkException($"{nameof(WeChatWebSignature)}，App:{request.App}，获取微信配置失败。");

            var ticket = await ticketManager.GetTicketAsync(request.App);

            var nonce = Str.GetNonceStr(16, isCharacter: false);

            var timestamp = DateTime.Now.ConvertToTimeStamp();

            var str = new StringBuilder();
            str.AppendFormat("jsapi_ticket={0}&", ticket);
            str.AppendFormat("noncestr={0}&", nonce);
            str.AppendFormat("timestamp={0}&", timestamp);
            str.AppendFormat("url={0}", request.Url);

            using var sha = SHA1.Create();
            var shaBytes = sha.ComputeHash(Encoding.UTF8.GetBytes(str.ToString()));
            string sign = BitConverter.ToString(shaBytes).Replace("-", "").ToLower();

            return new WebSignatureResult()
            {
                AppId = options.AppId,
                Nonce = nonce,
                TimeStamp = timestamp,
                Signature = sign
            };
        }
    }

    /// <summary>
    /// 签名请求
    /// </summary>
    public class WebSignatureRequest
    {
        /// <summary>
        /// 应用标识
        /// </summary>
        public string App { get; set; }
        /// <summary>
        /// 当前需要签名的页面完整URL地址
        /// </summary>
        public string Url { get; set; }
    }
    /// <summary>
    /// 分享数据参数
    /// </summary>
    public class WebSignatureResult
    {
        /// <summary>
        /// appid
        /// </summary>
        public string AppId { get; set; }
        /// <summary>
        /// 随机数字
        /// </summary>
        public string Nonce { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        public long TimeStamp { get; set; }
        /// <summary>
        /// 签名
        /// </summary>
        public string Signature { get; set; }
    }
}